import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Picker, ImageUploader, TextArea, Collapse } from 'antd-mobile';
import { AddOutline, DownOutline, UpOutline, ExclamationCircleOutline } from 'antd-mobile-icons';
import TagGroup from '../components/TagGroup';
import styles from './index.module.less';
import HeaderNav from "@/components/header-nav";
import { useSearchParams } from 'react-router-dom';
import { beforeUpload } from '@/utils/validate';
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const { getWorldBookDetails, uploadWorldImage, getUserWorldBookList, createWorldRole, getUserWorldBookDetails, editRole } = $globalServicer('world')
import OSS from 'ali-oss';
import { v4 as uuidv4 } from 'uuid';
import EditModal from '@/components/editModal';
import md5 from 'md5';
import { genderColumns, raceColumns, world_categoryColumns, era_backgroundColumns } from '@/utils/constant';
import TagSelector from '@/components/TagSelector';
import CreationMethod from '../components/creation-method';
import AiCreation from '../components/ai-creation';
import { handleImageUpload } from '@/utils/upload';
import { defaultRoleCover } from '@/utils/config';
// 生成随机文件名的函数
const generateRandomFileName = (file) => {
  const ext = file.name.split('.').pop() || '';
  const uuid = uuidv4();
  const hashName = md5(`${uuid}`);
  console.log("🚀 ~ generateRandomFileName ~ hashName:", hashName)
  return `images/${hashName}.${ext}`;
};

const CustomInput = ({ value, disabled, onClick, ...props }) => {
  return (
    <div
      className="custom-input-wrapper"
      onClick={disabled ? onClick : undefined}
      style={{
        position: 'relative',
        cursor: disabled ? 'pointer' : 'default'
      }}
    >
      <Input
        {...props}
        value={value}
        disabled={disabled}
      />
      {disabled && (
        <div
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            zIndex: 1,
          }}
        />
      )}
    </div>
  );
};
const WorldCreationForm = () => {
  const [roleForm] = Form.useForm();
  const [worldBookList, setWorldBookList] = useState([]);
  const [selectedTag, setSelectedTag] = useState(null);
  const [params] = useSearchParams();
  const [loading, setLoading] = useState(true)
  const id = params.get('id');
  const type = params.get('type');
  const roleId = params.get('roleId');
  console.log("🚀 ~ WorldCreationForm ~ roleId:", roleId)
  const customNavigate = $globalNavigate()
  const [submitting, setSubmitting] = useState(false)
  const [showAiInput, setShowAiInput] = useState(false)
  const [activeKey, setActiveKey] = useState('')
  const [initialValues, setInitialValues] = useState({
    cover: [{
      url: '',
      path: ''
    }],
    name: '',
    gender: '',
    age: '',
    race: '',
    appearance: '',
    background: '',
    experience: '',
    relationships: '',
    speaking_style: '',
    personality: '',
    preferences: '',
    motivation: '',
    abilities: '',
    world_category: '',
    world_era: '',
    world_map: '',
    world_faction: '',
    world_rules: '',
    custom_content: '',
    first_message: '',
  })
 
  useEffect(() => {
    if (id) {
      getUserWorldBookDetails(id).then(res => {
        let result = {
          ...res,
          ...res.description,
          cover: [
            {
              url: res.cover
            }
          ],
          gender: [res.description.gender],
          race: [res.description.race],
          world_category: [res.description.world_category],
          world_era: [res.description.world_era],
        }

        if (res.description.gender && !genderColumns.some(item => item.value == res.description.gender)) {
          genderColumns.push({ label: res.description.gender, value: res.description.gender })
        }

        if (res.description.race && !raceColumns.some(item => item.value == res.description.race)) {
          raceColumns.push({ label: res.description.race, value: res.description.race })
        }

        if (res.description.world_category && !world_categoryColumns.some(item => item.value == res.description.world_category)) {
          world_categoryColumns.push({ label: res.description.world_category, value: res.description.world_category })
        }

        if (res.description.world_era && !era_backgroundColumns.some(item => item.value == res.description.world_era)) {
          era_backgroundColumns.push({ label: res.description.world_era, value: res.description.world_era })
        }

        console.log("🚀 ~ getUserWorldBookDetails ~ result:", result)
        roleForm.setFieldsValue(result)
      });
      setActiveKey('1')
    } else {
      roleForm.setFieldsValue({
        cover: [
          {
            url: defaultRoleCover,
            path: defaultRoleCover
          }
        ]
      })
    }
  }, [])
  const onFinish = (values) => {
    if (submitting) return; // 如果正在提交，直接返回
    console.log("🚀 ~ onFinish ~ values:", values)
    let submitData = {
      name: values.name,
      cover: values.cover[0].url,
      description: {
        gender: values?.gender[0],
        age: values.age,
        race: values?.race?.[0],
        appearance: values.appearance,
        background: values.background,
        experience: values.experience,
        relationships: values.relationships,
        speaking_style: values.speaking_style,
        personality: values.personality,
        preferences: values.preferences,
        motivation: values.motivation,
        abilities: values.abilities,
        world_category: values?.world_category?.[0],
        world_era: values?.world_era?.[0],
        world_map: values.world_map,
        world_faction: values.world_faction,
        world_rules: values.world_rules,
        custom_content: values.custom_content,
      },
      first_message: values.first_message,
      type: 1,
    }
    console.log("🚀 ~ onFinish ~ submitData:", submitData)
    try {
      setSubmitting(true);
      if (id && type === 'edit') {
        submitData.id = id
        console.log("🚀 ~ ItemCrad ~ params:", submitData)
        editRole(submitData).then(res => {
          console.log(`------res`, res)
          showSuccessToast('编辑成功')
          customNavigate(`/world`)
        })
      } else {
        createWorldRole(submitData).then(res => {
          console.log(`------res`, res)
          showSuccessToast('创建成功')
          customNavigate(`/world`)
        })
      }
    } catch (error) {
      showErrorToast('提交失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };
  const [visible, setVisible] = useState(false)
  const [raceDisabled, setRaceDisabled] = useState(true)
  const [genderVisible, setGenderVisible] = useState(false)
  const [eraBackgroundVisible, setEraBackgroundVisible] = useState(false)
  const [worldTypeVisible, setWorldTypeVisible] = useState(false)
  const [isRequired, setIsRequired] = useState(true)
  // const [options, setOptions] = useState([
  //   { label: '火影忍者', value: 'naruto' },
  //   { label: '道果异仙', value: 'daoguo' },
  //   { label: '穿进豪门游戏后干掉BOSS', value: 'boss' },
  //   { label: '纳绘异能妃', value: 'nahui' },
  // ]);
  const handleAddOption = (newOptions) => {

  }
  // const handleAddOption = (newOption) => {
  //   setOptions(prev => [...prev, newOption]);
  //   // 这里可以调用API保存新选项到后端
  // };

  // 创建方式选择回调
  const handleSelMethod = (type) => {
    console.log("🚀 ~ handleSelMethod ~ type:", type)
    setShowAiInput(type === 'ai');
  }

  // 处理AI输入结果
  const handleAiResult = (res) => {
    console.log("🚀 ~ handleAiResult ~ result:", res)  
    let result = {
      ...res,
      ...res.description,
      cover: [],
      gender: res.description.gender ? [res.description.gender] : null,
      race: res.description.race ? [res.description.race] : null,
      world_category: res.description.world_category ? [res.description.world_category] : null,
      world_era: res.description.world_era ? [res.description.world_era] : null,
    }

    if (res.description.gender && !genderColumns.some(item => item.value == res.description.gender)) {
      genderColumns.push({ label: res.description.gender, value: res.description.gender })
    }

    if (res.description.race && !raceColumns.some(item => item.value == res.description.race)) {
      raceColumns.push({ label: res.description.race, value: res.description.race })
    }

    if (res.description.world_category && !world_categoryColumns.some(item => item.value == res.description.world_category)) {
      world_categoryColumns.push({ label: res.description.world_category, value: res.description.world_category })
    }

    if (res.description.world_era && !era_backgroundColumns.some(item => item.value == res.description.world_era)) {
      era_backgroundColumns.push({ label: res.description.world_era, value: res.description.world_era })
    }

    console.log("🚀 ~ getUserWorldBookDetails ~ result:", result)
    roleForm.setFieldsValue(result)
    setActiveKey('1')
  }
  return (
    <div className={styles.formContainer}>
      <div className="header">
        <HeaderNav backArrow={true} title={`${id && type === 'edit' ? "编辑" : "创建"}角色卡`}></HeaderNav>
      </div>

      {/* 智能创建输入框 */}
      <AiCreation show={showAiInput} type={1} onResult={handleAiResult} />

      <Form
        form={roleForm}
        onFinish={onFinish}
        footer={
          <div className={styles.footer}>
            <Button
              className={styles.submitButton}
              type='submit'
              loading={submitting}
              disabled={submitting}
            >{submitting ? '提交中...' : '完成'}</Button>
          </div>
        }
      >
        <div className={styles.imageItem}>
          <Form.Item name="cover" label="角色头像" required={isRequired} rules={[{ required: isRequired, message: '角色头像不能为空' }]}>
            <ImageUploader
              style={{ '--cell-size': '66px' }}
              className={styles.uploadWrapper}
              upload={handleImageUpload}
              maxCount={1}
              onDelete={() => {
                return { beforeDelete: () => true };
              }}
            />
          </Form.Item>
        </div>
        { /* 
        'gender' => '性别',
        'age' => '年龄',
        'race' => '种族',
        'appearance' => '外貌衣着',
        'background' => '人物背景',
        'experience' => '人物经历',
        'relationships' => '人际关系',
        'speaking_style' => '说话方式',
        'personality' => '性格特点',
        'preferences' => '人物喜好',
        'motivation' => '动机目标',
        'abilities' => '能力设定',
        'custom_content' => '自定义内容',
        'world_category' => '该角色所在世界分类',
        'world_era' => '该角色所在时代背景',
        'world_map' => '该角色所在世界地图',
        'world_faction' => '该角色所在主要势力',
        'world_rules' => '该角色所在世界特殊规则'

        */ }

        <Form.Item name="name" label="角色名称" help='字数上限40' required={isRequired} rules={[{ required: isRequired, message: '角色名称不能为空' }]}>
          <Input placeholder="输入角色名称，也是这张卡的名字。例1小美，例2丧彪（字数上限40）" maxLength={40} />
        </Form.Item>
        <TagSelector
          required={isRequired}
          rules={[{ required: isRequired, message: '性别不能为空' }]}
          name="gender"
          label="性别"
          help='字数上限20'
          maxCount={20}
          options={genderColumns}
          multiple={false}
          onAddOption={handleAddOption}
        />
        {/* <Form.Item name="gender" label="性别" help='' required={isRequired} rules={[{ required: isRequired, message: '性别不能为空' }]}>
          <Input placeholder="请选择性别" onClick={() => {
            setGenderVisible(true)
          }} />
        </Form.Item> */}
        <Form.Item name="age" label="年龄" help='字数上限20' required={isRequired} rules={[{ required: isRequired, message: '年龄不能为空' }]}>
          <Input placeholder="请输入年龄" maxLength={20} />
        </Form.Item>
        <Form.Item name="first_message" label="故事描述" help='字数上限1980' required={isRequired} rules={[{ required: isRequired, message: '故事描述不能为空' }]}>
          <TextArea
            placeholder="输入开启聊天后第一句对话，例1小美慵懒的躺在沙发上，这时，门铃响了...例2丧彪凶狠的问:“还有没有不服的？”（字数上限1980）"
            rows={4}
            maxLength={1980}
          />
        </Form.Item>
        {/* <Form.Item name="race" label="种族" help=''>
          <Input placeholder="请选择种族" onClick={() => {
            setVisible(true)
          }} />
        </Form.Item> */}
        <Collapse
          activeKey={activeKey}
          onChange={(activeKey) => {
            setActiveKey(activeKey)
          }}
        >
          <Collapse.Panel
            key='1'
            title={activeKey?.indexOf('1') ? '收起' : '展开'}
            className={styles.collapsePanelWrapper}
          
          >
            <TagSelector
              name="race"
              label="种族"
              help='字数上限40'
              maxCount={40}
              options={raceColumns}
              multiple={false}
              onAddOption={handleAddOption}
            />
            {/* 外貌衣着300字，人物背景300字，人物经历300字，
            人际关系300字，说话方式300字，性格特点300字，
            人物喜好300字，动机目标300字，能力设定300字 */}
            <Form.Item name="appearance" label="外貌衣着" help='字数上限600'>
              <TextArea rows={4}  placeholder="输入外貌衣着（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="background" label="人物背景" help='字数上限600'>
              <TextArea rows={4}  placeholder="输入人物背景（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="experience" label="人物经历" help='字数上限600'>
              <TextArea rows={4}  placeholder="输入人物经历（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="relationships" label="人际关系" help='字数上限600'>
              <TextArea rows={4} placeholder="输入人际关系（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="speaking_style" label="说话方式" help='字数上限600'>
              <TextArea rows={4}  placeholder="输入说话方式（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="personality" label="性格特点" help='字数上限600'>
              <TextArea rows={4}  placeholder="输入性格特点（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="preferences" label="人物喜好" help='字数上限600'>
              <TextArea rows={4} placeholder="输入人物喜好（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="motivation" label="动机目标" help='字数上限600'>
              <TextArea rows={4} placeholder="输入动机目标（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="abilities" label="能力设定" help='字数上限600'>
              <TextArea rows={4} placeholder="输入能力设定（字数上限600）" maxLength={600} />
            </Form.Item>
            <TagSelector
              name="world_category"
              label="该角色所在世界分类"
              options={world_categoryColumns}
              multiple={false}
              maxCount={40}
              help='字数上限40'
              onAddOption={handleAddOption}
            />
            {/* <Form.Item name="world_category" label="该角色所在世界分类">
          <Input placeholder="请选择该角色所在世界分类" onClick={() => {
            setWorldTypeVisible(true)
          }} />
        </Form.Item> */}
            <TagSelector
              name="world_era"
              label="该角色所在世界时代背景"
              maxCount={100}
              help='字数上限100'
              options={era_backgroundColumns}
              multiple={false}
              onAddOption={handleAddOption}
            />
            {/* <Form.Item name="world_era" label="该角色所在时代背景">
          <Input placeholder="请选择该角色所在时代背景" onClick={() => {
            setEraBackgroundVisible(true)
          }} />
        </Form.Item> */}
        {/* 该角色所在世界地图：50字，
        该角色所在世界主要势力300字，
        该角色所在世界特殊规则300字，
        自定义内容300字， */}
            <Form.Item name="world_map" label="该角色所在世界地图" help='字数上限100'>
              <TextArea rows={4} placeholder="输入该角色所在世界地图（字数上限100）" maxLength={100} />
            </Form.Item>
            <Form.Item name="world_faction" label="该角色所在主要势力" help='字数上限600'>
              <TextArea rows={4} placeholder="输入该角色所在主要势力（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="world_rules" label="该角色所在世界特殊规则" help='字数上限600'>
              <TextArea rows={4} placeholder="输入该角色所在世界特殊规则（字数上限600）" maxLength={600} />
            </Form.Item>
            <Form.Item name="custom_content" label="自定义内容" help='字数上限600'>
              <TextArea rows={4} placeholder="输入自定义内容（字数上限600）" maxLength={600} />
            </Form.Item>
          </Collapse.Panel>
        </Collapse>
      </Form>

      {/* <CreationMethod show={!id} onSelect={handleSelMethod}/> */}
    </div>
  );
};

export default WorldCreationForm;